package com.gigi.service.manual;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.Response;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gigi.entity.ExtraEntity;
import com.gigi.enums.*;
import com.gigi.mapper.manual.ExtraManualMapper;
import com.gigi.model.ExamineRequest;
import com.gigi.model.ExtraDO;
import com.gigi.model.ListExamineRequest;
import com.gigi.service.generated.ExtraService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ExtraManageService {

    private final ExtraService extraService;
    private final ExtraManualMapper extraManualMapper;
    private final AskForLeaveManageService askForLeaveManageService;

    public ExtraManageService(ExtraService extraService, ExtraManualMapper extraManualMapper,
                              AskForLeaveManageService askForLeaveManageService) {
        this.extraService = extraService;
        this.extraManualMapper = extraManualMapper;
        this.askForLeaveManageService = askForLeaveManageService;
    }

    /**
     * 新增接口
     *
     * @param request
     * @return
     */
    public Response insert(ExtraDO request) {

        LambdaQueryWrapper<ExtraEntity> wrapper = new LambdaQueryWrapper<ExtraEntity>()
                .eq(ExtraEntity::getSignInId, request.getSignInId())
                .eq(ExtraEntity::getUserId, request.getUserId())
                .orderByDesc(ExtraEntity::getId);
        List<ExtraEntity> list = extraService.list(wrapper);

        // 已有待审核 or 审核通过的申请，无需新增
        if (CollUtil.isNotEmpty(list)) {

            if (ExamineStateEnum.UN_CHECK.getCode().equals(list.get(0).getState())) {
                return Response.buildFailure(ErrorCodeEnum.UN_CHECK.getErrCode(), ErrorCodeEnum.UN_CHECK.getErrDesc());
            }

            if (ExamineStateEnum.PASS.getCode().equals(list.get(0).getState())) {
                return Response.buildFailure(ErrorCodeEnum.PASS.getErrCode(), ErrorCodeEnum.PASS.getErrDesc());
            }
        }

        ExtraEntity entity = new ExtraEntity();
        entity.setUserId(request.getUserId());
        entity.setSignInId(request.getSignInId());
        if (!extraService.save(entity)) {
            return Response.buildFailure(ErrorCodeEnum.SAVE_FAILED.getErrCode(), ErrorCodeEnum.SAVE_FAILED.getErrDesc());
        }
        return Response.buildSuccess();
    }

    /**
     * 学生补签申请列表接口
     *
     * @param request
     * @return
     */
    public MultiResponse<ExtraDO> listForStudent(ListExamineRequest request) {
        List<ExtraDO> extraDOS = extraManualMapper.listForStudent(request.getUserId());
        if (CollUtil.isNotEmpty(extraDOS)) {
            extraDOS.forEach(e -> {
                e.setTypeDesc(SignInTypeEnum.getEnumByCode(e.getType()).getDesc());
                e.setStartTimeStr(DateUtil.format(e.getStartTime(), DatePattern.NORM_DATETIME_PATTERN));
                e.setEndTimeStr(DateUtil.format(e.getEndTime(), DatePattern.NORM_DATETIME_PATTERN));
            });
        }
        return MultiResponse.of(extraDOS, extraDOS.size());
    }

    /**
     * 老师补签申请列表接口
     *
     * @param request
     * @return
     */
    public MultiResponse<ExtraDO> listForTeacher(ListExamineRequest request) {
        List<ExtraDO> extraDOS = extraManualMapper.listForTeacher(request.getUserId());
        if (CollUtil.isNotEmpty(extraDOS)) {
            extraDOS.forEach(e -> {
                e.setTypeDesc(SignInTypeEnum.getEnumByCode(e.getType()).getDesc());
                e.setStartTimeStr(DateUtil.format(e.getStartTime(), DatePattern.NORM_DATETIME_PATTERN));
                e.setEndTimeStr(DateUtil.format(e.getEndTime(), DatePattern.NORM_DATETIME_PATTERN));
            });
        }
        return MultiResponse.of(extraDOS, extraDOS.size());
    }

    /**
     * 审批接口
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Response examine(ExamineRequest request) {
        // 改审核状态
        ExtraEntity oldModel = extraService.getById(request.getId());
        ExtraEntity entity = new ExtraEntity();
        entity.setId(oldModel.getId());
        entity.setState(request.getState());
        extraService.updateById(entity);

        // 如果通过，改考勤状态为迟到
        if (YesOrNoEnum.YES.getCode().equals(request.getState())) {
            askForLeaveManageService.editRecordState(oldModel.getUserId(), oldModel.getSignInId(), SignInRecordStateEnum.LATE.getCode());
        }
        return Response.buildSuccess();
    }

}
